package com.example.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.course.dto.admin.*;
import com.example.course.pojo.Admin;
import com.example.course.pojo.Scores;
import com.example.course.pojo.User;
import com.example.course.service.AdminService;
import com.example.course.mapper.AdminMapper;
import com.example.course.utils.common.enums.Code;
import com.example.course.utils.common.enums.Jwt;
import com.example.course.utils.common.enums.Message;
import com.example.course.utils.common.result.PageResponseResult;
import com.example.course.utils.common.result.Result;
import com.example.course.utils.config.BaseContext;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author 24354
* @description 针对表【admin】的数据库操作Service实现
* @createDate 2024-03-15 20:26:06
*/
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Result login(AdminAdminLoginDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //查找数据
        Admin checkAdmin = adminMapper.selectOne(Wrappers.<Admin>lambdaQuery()
                .eq(Admin::getAdminName, dto.getName())
                .or().eq(Admin::getAdminPhone, dto.getName()));
        //密码加密
        String password=checkAdmin.getAdminSalt()+dto.getPassword();
        password = DigestUtils.md5Hex(password);
        //异常抛出
        if (!checkAdmin.getAdminPassword().equals(password)) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        //token封装
        String token = Jwts.builder()
                .setHeaderParam(Message.Jwt_Typ, Jwt.Admin_Jwt_Key.getTyp())
                .setHeaderParam(Message.Jwt_Alg,Jwt.Admin_Jwt_Key.getAlg())
                .setSubject(Jwt.Admin_Jwt_Key.getName())
                .setExpiration(new Date(System.currentTimeMillis()+Jwt.Admin_Jwt_Key.getExp()))
                .claim(Message.Admin_id,checkAdmin.getAdminId())
                .signWith(SignatureAlgorithm.HS256,Jwt.Admin_Jwt_Key.getKey())
                .compact();
        return Result.okResult(token);
    }

    @Override
    public Result saveAdmin(AdminAdminSaveDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        Long adminId = BaseContext.getCurrentId();
        Admin checkAdmin = adminMapper.selectById(adminId);
        if (adminId==null||checkAdmin==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //添加是否重复
        List<Admin> checkNewAdmin = adminMapper.selectList(Wrappers.<Admin>lambdaQuery()
                .eq(Admin::getAdminNick, dto.getNick())
                .or().eq(Admin::getAdminName, dto.getName()));
        if (!CollectionUtils.isEmpty(checkNewAdmin)||checkNewAdmin.size()>0) {
            return Result.errorResult(Code.DATA_EXIST);
        }
        //未重复构建实体
        Admin admin=new Admin();
        admin.setAdminNick(dto.getNick());
        admin.setAdminName(dto.getName());
        admin.setPassword(dto.getPassword());
        admin.setAdminSalt(checkAdmin.getAdminName());
        admin.setAdminPassword(DigestUtils.md5Hex(checkAdmin.getAdminName()+dto.getPassword()));
        admin.setAdminPhone(dto.getPhone());
        //添加
        int check = adminMapper.insert(admin);
        if (check==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getAdminUser(AdminUserListDto dto) {
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //充值页码
        dto.checkParam();
        //构建page
        IPage page=new Page(dto.getPage(),dto.getSize());
        //获取数据库
        LambdaQueryWrapper<Admin> wrapper=new LambdaQueryWrapper<>();
        if (dto.getMemo()!=null) {
            wrapper.like(Admin::getAdminPhone,dto.getMemo());
            wrapper.or().like(Admin::getAdminNick,dto.getMemo());
        }
        wrapper.orderByDesc(Admin::getAdminId);
        //注入数据
        page=page(page,wrapper);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public Result removeAdminUser(AdminUserRemoveDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //删除数据是否存在
        Admin check = adminMapper.selectById(dto.getId());
        if (check==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        //删除数据
        int checkRemove = adminMapper.deleteById(dto.getId());
        if (checkRemove==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result updateAdmin(AdminUpdateDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //获取修改信息
        Admin checkAdmin = adminMapper.selectById(dto.getAdminId());
        if (checkAdmin==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        //构建修改参数
        Admin admin=new Admin();
        String password = DigestUtils.md5Hex(checkAdmin.getAdminSalt() + dto.getPassword());
        admin.setAdminId(dto.getAdminId());
        admin.setAdminPassword(password);
        admin.setPassword(dto.getPassword());
        log.info("checkPassword:{}",password);
        log.info("checkAdmin:{}",admin);
        int checkUpdate = adminMapper.updateById(admin);
        if (checkUpdate==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }
}




